﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shape.Mvp.Views;
using System.Windows.Forms;

namespace Shape.Mvp
{
   public interface IWindowMode
   {
      void AsMainWindow();
      void AsDialog();
      void AsForm();
   }

   internal class WindowManager : IWindowMode
   {
      private Form _currentView;
      private Form _mainWindow;
		private Form _currentParent;

      private HashSet<Form> _openForms = new HashSet<Form>();

      public IWindowMode Show(IView view)
      {
         _currentView = view as Form;

         return Show(_currentView);
      }

      public IWindowMode Show(Form form)
      {
         _currentView = form;

         if (_currentView == null)
         {
            throw new InvalidCastException();
         }

         _currentView.Activated += OnWindowActivated;

         return this;
      }

      void IWindowMode.AsMainWindow()
      {
         _mainWindow = _currentView as Form;

         System.Windows.Forms.Application.Run(_currentView as Form);
      }

      void IWindowMode.AsDialog()
      {
			if (_currentParent != null)
			{
				_currentView.ShowDialog(_currentParent);    
			}
			else
			{
				_currentView.ShowDialog(_mainWindow);    
			}
         
      }

		void IWindowMode.AsForm()
		{
         _currentView.FormClosed += OnFormClosed;

			_currentView.Show(_mainWindow);

         _openForms.Add(_currentView);
		}

      private void OnFormClosed(object sender, FormClosedEventArgs e)
      {
         _openForms.Remove(sender as Form);
      }

		private void OnWindowActivated(object sender, EventArgs e)
		{
			_currentParent = sender as Form;
		}
   }
}
